<template>
  <div class="pgmain">
    <!-- 上肢功能评估量表 UEFI  -->
    <div class="pgquestionbox beautifulScroll">
      <a-form ref="formRef" :rules="formRules" :model="formModel">
        <div class="pgquestion" v-for="(item, index) in pgdata" :key="item.id">
          <a-form-item :field="String(item.id)">
            <div class="pgname">{{ item.name }}</div>
            <div class="pgchoicebox">
              <a-radio-group
                :disabled="Evaluationshow"
                v-model="formModel[item.id]"
                :options="item.des"
              ></a-radio-group>
            </div>
          </a-form-item>
        </div>
      </a-form>
    </div>
    <div class="pgckbox beautifulScroll">
      <img
        ref="nativeImg"
        src="@/assets/images/mmse.png"
        style="display: none"
      />
      <!-- <img src="@/assets/images/guanjieyan.png" alt="" class="pgckboximg" /> -->
      <a-image class="pgckzz" :src="nativeImg?.src" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { saveEvaluation } from '@/api/pingu';
  const nativeImg = ref<HTMLImageElement | null>(null);
  const title = ref('MMSE评分量表');
  const props = defineProps({
    // 定义patientTreatmentId属性，指定类型为字符串
    patientTreatmentId: {
      type: String,
      required: true, // 如果父组件必须传递该属性，可设为true
      // 可选：设置默认值（当required为false时生效）
      // default: 'default-id'
    },
    Evaluationshow: {
      type: Boolean,
    },
    Evaluationdata: {
      type: Object,
    },
  });
  const Evaluationshow = ref(props.Evaluationshow);
  const patientTreatmentId = ref(props.patientTreatmentId);
  const Evaluationdata = ref(props.Evaluationdata);
  const pgdata = [
    {
      id: 1,
      name: '1、星期几(I定向力)',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 2,
      name: '2、几号(I定向力)',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 3,
      name: '3、几月(I定向力)',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 4,
      name: '4、什么季节(I定向力)',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 5,
      name: '5、哪一年(I定向力)',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 6,
      name: '6、省市(I定向力)',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 7,
      name: '7、区县(I定向力)',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 8,
      name: '8、街道或乡(I定向力)',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 9,
      name: '9、什么地方(I定向力)',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 10,
      name: '10、第几层楼(I定向力)',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 11,
      name: '11、皮球(II记忆力)',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 12,
      name: '12、国旗(II记忆力)',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 13,
      name: '13、树木(II记忆力)',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 14,
      name: '14、100-7（III注意力和计算力）',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 15,
      name: '15、-7（III注意力和计算力）',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 16,
      name: '16、 -7（III注意力和计算力）',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 17,
      name: '17、-7（III注意力和计算力）',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 18,
      name: '18、-7（III注意力和计算力）',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 19,
      name: '19、皮球（IV回忆能力）',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 20,
      name: '20、国旗（IV回忆能力）',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 21,
      name: '21、树木（IV回忆能力）',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 22,
      name: '22、命名能力（V语言能力）',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 23,
      name: '23、命名能力（V语言能力）',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 24,
      name: '24、复述能力（V语言能力）',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 25,
      name: '25、三步命令（V语言能力）',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 26,
      name: '26、三步命令（V语言能力）',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 27,
      name: '27、三步命令（V语言能力）',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 28,
      name: '28、阅读能力（V语言能力）',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 29,
      name: '29、书写能力（V语言能力）',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
    {
      id: 30,
      name: '30、结构能力（V语言能力）',
      des: [
        { label: '0', value: '0' },
        { label: '1', value: '1' },
      ],
    },
  ];
  // 评估名称

  const formRef = ref();
  const formModel = ref<Record<string, string>>({});
  const formRules: Record<string, any[]> = {};

  pgdata.forEach((item) => {
    formModel.value[item.id] = '';
    formRules[item.id] = [
      { required: true, message: '必填', trigger: 'change' },
    ];
  });
  if (Evaluationdata.value && Object.keys(Evaluationdata.value).length > 0) {
    // 只有当Evaluationdata.value存在且不是空对象时才赋值
    formModel.value = { ...Evaluationdata.value };
    console.log('查看模式回显的数据处理完成', formModel.value);
  }
  const scoresSum = ref(0);
  // 计算总和的方法
  const calculateSum = () => {
    let sum = 0;

    // 1. 先获取所有type='tk'的项的id（转为字符串，与表单键名匹配）
    const tkItemIds = pgdata
      .filter((item: any) => item.type === 'tk')
      .map((item) => item.id.toString());

    // 2. 遍历表单数据，排除tk项和空值
    Object.entries(formModel.value).forEach(([key, value]) => {
      // 跳过条件：是tk项 或 值为空
      if (tkItemIds.includes(key) || value == '' || value == undefined) {
        return;
      }

      // 累加有效数值
      sum += Number(value);
    });

    scoresSum.value = sum;
    console.log('当前成绩', scoresSum.value);
  };

  //提交评估表
  const submitPg = () => {
    // 返回Promise以便父组件捕获状态
    return new Promise((resolve, reject) => {
      formRef.value.validate((errors: any) => {
        if (!errors) {
          // 初始计算一次
          calculateSum();

          saveEvaluation({
            patientTreatmentId: patientTreatmentId.value,
            evaluation: JSON.stringify(formModel.value),
            title: title.value,
            score: scoresSum.value,
          })
            .then((res: any) => {
              if (res.code == 200) {
                console.log('提交评估成功', res.data);
                resolve(res.data); // 成功时返回数据
              } else {
                // 接口返回非200状态视为失败
                reject(new Error(`提交失败: ${res.msg || '未知错误'}`));
              }
            })
            .catch((error: any) => {
              // 捕获接口调用异常
              console.error('提交评估失败', error);
              reject(new Error(`网络错误: ${error.message}`));
            });
        } else {
          // 表单验证失败
          reject(new Error('表单验证失败，请检查输入'));
        }
      });
    });
  };
  defineExpose({
    submitPg,
  });
</script>

<style scoped>
  .pgmain {
    height: 100%;
    display: flex;
  }
  .pgckbox {
    height: 600px;
    width: 600px;
    overflow: hidden;
    overflow-y: auto;
  }

  :deep(.pgckzz .arco-image-img) {
    width: 590px;
    height: 725px;

    cursor: pointer;
  }
  .pgquestionbox {
    width: 600px;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    height: 600px;
  }
  .pgckboximg {
    width: 590px;
    height: 1301px;
    position: absolute;
    top: 0px;
    left: 0px;
    cursor: pointer;
  }
  .pgquestion {
    display: flex;
    flex-direction: column;
  }
  .pgname {
    font-size: 18px;
  }
  .pgchoicebox {
    display: flex;
    font-size: 18px;
    margin-top: 10px;
  }
  :deep(.pgchoicebox .arco-radio-label) {
    font-size: 18px !important;
  }

  :deep(.pgquestionbox .arco-form-item-content-flex) {
    flex-direction: column !important;
    align-items: normal !important;
    justify-content: normal !important;
  }

  :deep(.pgquestionbox .arco-col-5) {
    flex: 0 !important;
    width: 0 !important;
  }
</style>
